import 'package:flutter/material.dart';
import 'package:flutter_app/module/home/marker/content/view.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'state.dart';

class MarkerLogic extends GetxController with SingleGetTickerProviderMixin  {
  final state = MarkerState();

  RxList<String> tabs = RxList<String>();
  TabController? tabController;
  PageController? _pageController;

  Widget? tabBar;
  Widget? pageView;

  @override
  void onInit() {
    super.onInit();
    getTabsAndPageView();
  }

  @override
  void onClose() {
    super.onClose();
    tabController?.dispose();
    _pageController?.dispose();
  }

  void getTabsAndPageView() async {
    var list = await Future.delayed(Duration(seconds: 2),
        () => ["机会", "港股", "美股", "泸深", "泸深港通", "期货", "外汇", "指数", "债券"]);

    tabs.value = list;
    tabController = TabController(length: tabs.value.length, vsync: this);
    tabBar = _buildTabs();
    update(["tabBar"]);

    _pageController = PageController();
    pageView = _buildPageView();
    update(["content"]);

    tabController!.addListener(() {
      if (tabController!.index == tabController!.animation!.value) {
        _pageController!.jumpToPage(tabController!.index);
      }
    });
  }

  _buildTabs() {
    return TabBar(
        physics: null,
        indicatorColor: Colors.blue,
        isScrollable: true,
        controller: tabController,
        tabs: tabs.value.map((e) {
          return Tab(text: e);
        }).toList());
  }

  _buildPageView() {
    return PageView(
      onPageChanged: (pos) {
        tabController!.animateTo(pos);
      },
      controller: _pageController,
      children: tabs.value.map((e) => _buildContent(e)).toList(),
    );
  }

  Widget _buildContent(String e) {
    return ContentPage(id: e);
  }
}
